package com.cn.shiro_jwt_redis.comm.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {

    public static final long EXPIRE_TIME=5*60*1000;//accessToken到期时间为5分钟，单位毫秒
    public static final long REFRESH_EXPIRE_TIME=30*60;//refreshToken到期时间为30分钟，单位秒
    public static final String Token_SELECT="kjfkf%^**454545!!!";

    /**
     * 生成token
     * @param account
     * @param currentTime
     * @return token
     */
    public static  String sign(String account,Long currentTime){
        String token=null;
        try {
            Date expireAt=new Date(currentTime+EXPIRE_TIME);
            token= JWT.create()
                    .withIssuer("zkp")//发行人
                    .withClaim("account",account)//存放数据
                    .withClaim("currentTime",currentTime)//当前时间戳
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(Token_SELECT));
        }catch (IllegalArgumentException| JWTCreationException je){

        }
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return true
     * @throws Exception
     */
    public static boolean verify(String token)throws Exception{

        //创建token验证器
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(Token_SELECT)).withIssuer("zkp").build();
        DecodedJWT decodedJWT=jwtVerifier.verify(token);
        return true;
    }


    /**
     * 获取token中的用户
     * @param token
     * @return account
     */
    public static String getAccount(String token){
        try {
            DecodedJWT decodedJWT=JWT.decode(token);//获取token中存储的map集合
            return decodedJWT.getClaim("account").asString();//通过相对应的键获得值
        }catch (JWTCreationException e){
            return null;
        }
    }

    /**
     * 获取时间戳
     * @param token
     * @return currentTime
     */
    public static Long getCurrentTime(String token){
        try{
            DecodedJWT decodedJWT=JWT.decode(token);
            return decodedJWT.getClaim("currentTime").asLong();

        }catch (JWTCreationException e){
            return null;
        }
    }
}
